import React, { useState, useEffect } from 'react';
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Row,
  Col,
  TreeSelect,
  Upload,
  Radio,
  InputNumber,
} from 'antd';
import local from '@/utils/local';
import {
  addField,
  upadataField,
  sysDeptAllTree,
  cmsColumnAllTree,
  cmsTemplateList,
  getDetail,
} from '../api';
import styles from '../index.less';

const { SHOW_ALL } = TreeSelect;
/**
 * @zh-CN 部门同步树
 *
 * @param datas
 */

const setTreeFormat = datas => {
  const newData = [];

  datas.map(item => {
    const obj = {
      id: item.deptId,
      value: item.deptId,
      pId: item.parentId,
      title: item.deptName,
    };
    if (item.children && item.children.length) {
      obj.children = setTreeFormat(item.children);
    }
    newData.push(obj);
    return '';
  });
  return newData;
};
/**
 * @zh-CN 栏目同步树格式化
 *
 * @param datas
 */

const setColumnTreeFormat = datas => {
  const newData = [];
  datas.map(item => {
    const obj = {
      id: item.columnId,
      value: item.columnId,
      pId: item.parentId,
      title: item.columnName,
    };
    if (item.children && item.children.length) {
      obj.children = setColumnTreeFormat(item.children);
    }
    newData.push(obj);
    return '';
  });
  return newData;
};

const UpdateFormA = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type } = props;

  const { currentIndex = 0 } = data;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [fileList, setFileList] = useState([]);
  const [dept, setDept] = useState(); //  站点树处理
  const [sysDeptAllTreeData, setSysDeptAllTreeData] = useState(); // 部门同步树

  const [column, setColumn] = useState(); //  栏目
  const [cmsColumnAllTreeData, setcmsColumnAllTreeData] = useState(); // 栏目同步树

  const [columnImg, setColumnImg] = useState();

  // const [templateId, setTemplateId] = useState(); //  模板
  const [cmsTemplateListData, setcmsTemplateListData] = useState([]); // 栏目同步树

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  // 详情
  const getDetailData = () => {
    getDetail(data.columnId).then(res => {
      if (res.code === 0) {
        const newdept = [];
        const depts = data.depts || [];
        depts.map(item => {
          newdept.push(item.deptId * 1);
          return '';
        });

        if (data.imageUrl) {
          setFileList([
            {
              uid: `tmp-${1}`,
              name: '栏目图片',
              // eslint-disable-next-line no-undef
              url: `${baseUrl}${data.imageUrl}`,
              postUrl: data.imageUrl,
              status: 'done',
            },
          ]);
        } else {
          setFileList([]);
        }

        setColumn(data.parentId);
        setDept(newdept);
        form.setFieldsValue({ ...data, templateId: res.data.templateId });
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };
  /**
   * @zh-CN 同步获取部门树
   *
   * @param fields
   */
  const getSysDeptAllTree = async fields => {
    try {
      const res = await sysDeptAllTree({ ...fields });
      if (res.code === 0) {
        setSysDeptAllTreeData(setTreeFormat([res.data]));
        return;
      }
    } catch (error) {
      message.error('获取部门失败，请重试');
      return false;
    }
  };

  /**
   * @zh-CN 同步获取栏目树
   *
   * @param fields
   */
  const getcmsColumnAllTree = async fields => {
    try {
      const res = await cmsColumnAllTree({ ...fields });
      if (res.code === 0) {
        setcmsColumnAllTreeData(setColumnTreeFormat(res.data));
        return;
      }
    } catch (error) {
      message.error('获取站点失败，请重试');
      return false;
    }
  };

  /**
   * @zh-CN 模板列表
   *
   * @param fields
   */
  const getCmsTemplateList = async fields => {
    try {
      const res = await cmsTemplateList({ ...fields });
      if (res.code === 0) {
        setcmsTemplateListData(res.data);
        return;
      }
    } catch (error) {
      message.error('获取模板失败，请重试');
      return false;
    }
  };

  // 选择部门
  const deptOnChange = value => {
    setDept(value);
  };

  // 选择栏目
  const columnOnChange = value => {
    setColumn(value);
  };

  useEffect(() => {
    setDept();
    setColumn();
    setFileList([]);
    if (!sysDeptAllTreeData && visible) {
      getSysDeptAllTree();
    }
    if (!cmsColumnAllTreeData && visible) {
      getcmsColumnAllTree();
    }
    if (cmsTemplateListData.length === 0 && visible) {
      getCmsTemplateList();
    }

    form.setFieldsValue({ audit: 0, orderNum: currentIndex });
    if (type === 'updata' && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
      form.setFieldsValue({ audit: 0 });
    }
  }, [visible]);

  const accessToken = local.get('token');

  const coverImageProps = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    showUploadList: true,
    listType: 'picture-card',
    fileList,
    data: { businessType: 'cms', fileName: 'fileName' },
    // eslint-disable-next-line no-undef
    action: `${API_PREFIX}/upload`,
    onChange: ({ fileList: newFileList }) => {
      setFileList(newFileList);
    },
    accept: 'image/gif,image/jpeg,image/png',
    multiple: 1,
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = (values, imageUrl) => {
    const hide = message.loading('正在添加');
    setLoading(true);
    values.img = null;
    upadataField({
      ...values,
      columnId: data.columnId,
      parentId: column,
      deptIds: dept,
      imageUrl,
    }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = (values, imageUrl) => {
    const hide = message.loading('正在添加');
    setLoading(true);
    values.img = null;
    addField({ ...values, parentId: column, deptIds: dept, imageUrl }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '添加失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      const imageUrl = fileList[0]?.response?.data?.fileUrl || fileList[0]?.postUrl;
      if (type === 'updata') updataData(values, imageUrl);
      if (type === 'add') addData(values, imageUrl);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button onClick={sendData} type="primary" loading={loading} disabled={loading}>
              保存
            </Button>
          </div>
        }
      >
        <Form {...formItemLayout} name="control-ref" form={form}>
          {visible && (
            <div className={styles.treeBox}>
              <Row>
                <Col span={14} push={4}>
                  <TreeSelect
                    treeData={sysDeptAllTreeData}
                    placeholder="选择部门"
                    value={dept}
                    showCheckedStrategy={SHOW_ALL}
                    style={{ width: 340 }}
                    allowClear
                    multiple
                    showSearch
                    treeCheckable={true}
                    // treeDefaultExpandAll
                    onChange={(value, label, extra) => {
                      deptOnChange(value, label, extra);
                    }}
                  />
                </Col>
                <Col span={4} pull={14}>
                  <div className={styles.treeName}>
                    <em className="star">*</em>选择部门：
                  </div>
                </Col>
              </Row>
            </div>
          )}
          {visible && (
            <div className={styles.treeBox}>
              <Row>
                <Col span={14} push={4}>
                  <TreeSelect
                    treeData={cmsColumnAllTreeData}
                    placeholder="父级栏目"
                    value={column}
                    style={{ width: 340 }}
                    showSearch
                    onChange={(value, label, extra) => {
                      columnOnChange(value, label, extra);
                    }}
                    allowClear
                  />
                </Col>
                <Col span={4} pull={14}>
                  <div className={styles.treeName}>父级栏目：</div>
                </Col>
              </Row>
            </div>
          )}
          <Form.Item label="栏目名称" name="columnName" rules={[{ required: true }]}>
            <Input maxLength={20} allowClear />
          </Form.Item>
          <Form.Item label="栏目图片">
            <Form.Item name="img" noStyle>
              <Upload name="file" {...coverImageProps}>
                {fileList.length < 1 && <>Upload</>}
              </Upload>
            </Form.Item>
          </Form.Item>
          <Form.Item width="xs" name="orderNum" label="显示顺序" rules={[{ required: true }]}>
            <InputNumber min={0} max={1000} />
          </Form.Item>
          <Form.Item name="templateId" label="选择模板" rules={[{ required: true }]}>
            <Radio.Group>
              {cmsTemplateListData.map(item => (
                <div className={styles.temsBox} key={item.templateId}>
                  <Radio value={item.templateId * 1}>
                    <p>{item.templateName}</p>
                    {item.templateImg.split(',') && item.templateImg.split(',')[0] && (
                      <img
                        src={`${baseUrl}${item.templateImg.split(',')[0]}`}
                        style={{ width: 100, marginRight: 10 }}
                      />
                    )}
                    {item.templateImg.split(',') && item.templateImg.split(',')[1] && (
                      <img
                        src={`${baseUrl}${item.templateImg.split(',')[1]}`}
                        style={{ width: 100 }}
                      />
                    )}
                  </Radio>
                </div>
              ))}
            </Radio.Group>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default UpdateFormA;
